import interact from "@/utils/interact";
import { userLogin, getUserInfo } from "@/api/user";
// @ts-ignore 忽略类型检查，因为store模块没有类型声明文件
import Store from "@/store/index";


export const logout = () => {
    Store.commit("user/CLEAR_USER_ACCOUNT");
    Store.commit("user/CLEAR_USER_INFO");
}

export const getUserInfoFn = (token?: string) => {
    if (!token) token = Store.state.user.account.token;
    return new Promise((resolve, reject) => {
        getUserInfo({ token: token }).then((res) => {
            Store.commit("user/SET_USER_INFO", res.data);
            resolve(res.data);
        }, err => {
            reject(err);
        });
    });
};

/**
 * 全局登录
 * @param {Boolean} tip 是否弹窗提示
 * */
export const globalLogin = (tip?: boolean) => {
    return new Promise((resolve, reject) => {
        const loginApi = async (loginRes: any) => {
            if (!Store.state.shop.storeNo) {
                return interact.modal("门店信息不能为空").then(() => {
                    uni.reLaunch({
                        url: "/pages/index/index",
                    });
                });
            }
            uni.showLoading({ mask: true, title: "登录中..." });
            userLogin(
                {
                    platform: "03",
                    platCode: Store.state.shop.platCode,
                    loginData: JSON.stringify({
                        code: loginRes.authCode,
                        iv: "",
                        encryptData: "",
                    }),
                    storeNo: Store.state.shop.storeNo,
                },
                {
                    complete: () => {
                        uni.hideLoading();
                    },
                }
            ).then(
                async (checkRes) => {
                    const data = checkRes.data.login;
                    if (data.userId) {
                        Store.commit("user/SET_USER_ACCOUNT", data);
                        await getUserInfoFn()
                        resolve(true)
                    } else {
                        Store.commit("user/SET_TEMP_USER_ACCOUNT", data);
                        Store.commit( "user/SET_LOGIN_BIND_PHONE_PROMISE_RESOLVE", resolve );
                        uni.navigateTo({
                            url: "/pages/login/login",
                        });
                    }
                },
                (err: any) => {
                    console.log(err);

                    interact.toast(err.msg);
                }
            );
        };
        // #ifdef MP-ALIPAY
        my.getAuthCode({
            scopes: ["auth_base", "auth_user"],
            success: async (res: any) => {
                if (tip === true) {
                    interact
                        .modal({
                            title: "温馨提示",
                            message: "您还未登录，请先登录",
                            showCancel: true,
                        })
                        .then((action) => {
                            if (action.confirm) {
                                loginApi(res);
                            }
                        });
                } else {
                    loginApi(res);
                }
            },
        });
        // #endif

        // #ifdef APP-PLUS || H5
        uni.navigateTo({
            url: "/pages/login/mobile",
        })
        Store.commit( "user/SET_LOGIN_BIND_PHONE_PROMISE_RESOLVE", resolve );

        console.log(123123);

        // #endif
    });
};



export const getLoginStatus = (toLogin?: boolean) => {
    return new Promise((resolve, reject) => {
        if (Store.state.user.account.token) {
            resolve(true);
        } else {
            if (toLogin) {
                uni.showModal({
                    title: "提示",
                    content: "必须要登录后，才能继续操作",
                    confirmText: "一键登录",
                    success: async (action) => {
                        if (action.confirm) {
                            await globalLogin();
                            resolve(true);
                        } else {
                            resolve(false);
                        }
                    },
                });
            } else {
                resolve(false);
            }
        }
    });
};
